/**
 * 
 */
package com.iwords.api.web.filter;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import javax.ejb.EJB;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;

import org.json.JSONException;
import org.json.JSONObject;

import com.iwords.service.UserServiceLocal;
import com.iwords.service.object.UserEntity;
import com.iwords.utils.CodeUtils;
import com.iwords.utils.StringUtils;

/**
 * @author qianxiang
 *
 */

@WebFilter(urlPatterns={"/*"},initParams={@WebInitParam(name="exceptUrlPatterns",value="/api/user,/api/alipayNotifyAPI,/api/alipayStartAPI,/api/alipayDiscountAPI,/api/alipayReturnAPI")})
public class CheckUserFilter implements Filter{
	@EJB
	UserServiceLocal userService;
	
	private Set<String> exceptUrlPatterns = new HashSet<String>();

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain) throws IOException, ServletException {
		
		if (checkUser(req, res)) {
			filterChain.doFilter(req, res);
		} else {

			JSONObject result = new JSONObject();
			try {
				result.put("needPay", "true");
			} catch (JSONException e) {

			}
			res.getWriter().print(result.toString());
			res.getWriter().flush();
		}
		
	}

	private boolean checkUser(ServletRequest req, ServletResponse res) {
		
		if(exceptUrlPatterns.contains(((HttpServletRequest)req).getRequestURI())){
			return true;
		}
		
		String useridStr = req.getParameter("userid");
		Long userid = null;
		
		if (StringUtils.isNotBlank(useridStr)) {

			userid = Long.parseLong(useridStr);

		}
		if(userid == null){
			return true;
		}
		
		UserEntity user = userService.find(userid);
		if(user==null || user.getUserVacation()==null || !user.getUserVacation().isValid()){
			return false;
		}else{
			return true;
		}
		
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		String exceptUrls = filterConfig.getInitParameter("exceptUrlPatterns");
		String[] exceptUrlArray = exceptUrls.split(",");
		exceptUrlPatterns.addAll(Arrays.asList(exceptUrlArray));
	}
	
}
